import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { from, map, Observable, switchMap } from 'rxjs';

type ActionDefinition = {
  id: number | string;
  type: string;
  name: string;
  description: string;
  createdAt: string
};
type InsertDataDefinition = {
  data: ActionDefinition,
  code: number,
  message: string
}

@Injectable()
export class KnowledgeTransformInterceptor implements NestInterceptor {

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {

    // 基本配置
    const request = context.switchToHttp().getRequest();
    const host = process.env.KNOWLEDGE_BASE_HOST;
    const apiKey = process.env.KNOWLEDGE_BASE_API_KEY;
    const dataset_id = process.env.KNOWLEDGE_BASE_DATASET_ID;
    const template_document_id = process.env.KNOWLEDGE_BASE_TEMPLATE_DOC_ID;
    const kit_document_id = process.env.KNOWLEDGE_BASE_KIT_DOC_ID;
    const documentMappings = {
      '/api/template/track': template_document_id,
      '/api/kits': kit_document_id
      // Add more mappings here as needed
    };
    // 单独处理需要额外处理的请求
    const matchedPath = Object.keys(documentMappings).find(path => request.url.includes(path));
    if (matchedPath) {

      return next.handle().pipe(
        switchMap((insertedData: InsertDataDefinition) => {
          console.log(insertedData,"insertedData")
          if (!insertedData?.data) {
            return next.handle(); // 直接返回原始流程
          }
          const templateSchema = this.createActionDefinition('Action', insertedData.data)
          const common = insertedData.data.name + "\n```typescript\n" + templateSchema + "\n```"
          const difyContent = { segments: [{ "content": common }] }
          const documentId = request.url.includes('/api/kits') ? kit_document_id : template_document_id

          return from(fetch(`${host}/v1/datasets/${dataset_id}/documents/${documentId}/segments`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${apiKey}`
            },
            body: JSON.stringify(difyContent)
          })).pipe(
            switchMap(async (response: Response) => {
              if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
              }
              return await response.json();
            }),
            map((externalResponse) => ({
              data: {
                localInsert: insertedData,
                externalResponse
              },
              code: context.switchToHttp().getResponse().statusCode
            }))
          );
        })
      );
    }

    return next.handle();
  }
  // 拼接TS定义
  createActionDefinition(prefix: string, entity: ActionDefinition): string {
    return `export type ${prefix}${entity.name} = {
    id: '${entity.id}';
    type: '${entity.type}';
    name: '${entity.name}';
    description: '${entity.description}';
    createdAt:'${entity.createdAt}'
};`;
  }
}
